﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using QLKDS.DAL;
using DevExpress.XtraBars;

namespace QLKDS.Forms
{
    public partial class frmAuthors : Form
    {
        #region Properties
        private AuthorManager authorsManager;

        #endregion


        #region Methods

        public frmAuthors()
        {
            InitializeComponent();

            this.authorsManager = new AuthorManager();
            this.grvAuthor.GroupPanelText = "Kéo một cột vào đây để nhóm dữ liệu";

        }

        private void frmAuthors_Load(object sender, EventArgs e)
        {
            // Population data on Author gridview
            this.PopulateAuthorGridView();
        }

        private void frmAuthors_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmMain.MainWindowManager.WindowNames.Remove(this.Name);
            frmMain.MainWindowManager.Windows.Remove(this);
        }

        public void PopulateAuthorGridView()
        {
            this.Cursor = Cursors.WaitCursor;

            this.gridAuthor.DataSource = this.authorsManager.ListAuthor();

            this.Cursor = Cursors.Default;
        }

        #endregion



        private void btnAdd_Click(object sender, EventArgs e)
        {
            var form = new frmAuthorsAdd(this);
            form.ShowDialog();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            int row = (int)grvAuthor.FocusedRowHandle;
            var form = new frmAuthorsEdit();
            if (row >= 0)
            {
                int id = int.Parse((grvAuthor.GetRowCellValue(row, grvAuthor.Columns["Id"]) + "").ToString());

                form.Authors = this.authorsManager.GetAuthorsById(id);
            }

            if (form.ShowDialog() == DialogResult.OK)
            {
                this.PopulateAuthorGridView();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int row = (int)grvAuthor.FocusedRowHandle;
            if (row >= 0)
            {
                int id = int.Parse((grvAuthor.GetRowCellValue(row, grvAuthor.Columns["Id"]) + "").ToString());

                string name = (grvAuthor.GetRowCellValue(row, grvAuthor.Columns["Name"]) + "").ToString();

                if (XtraMessageBox.Show("Bạn có muốn xóa tác giả : " + name + " không?", "Xác nhận xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    this.authorsManager.DeleteAuthors(id);
                    this.PopulateAuthorGridView();
                    XtraMessageBox.Show("Xóa dữ liệu thành công");
                }
            }   
        }

     
    }
}
